package com.horsen.service.user.controller.admin;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.horsen.common.util.JwtInfo;
import com.horsen.common.util.JwtUtils;
import com.horsen.common.util.R;
import com.horsen.common.util.ResultCodeEnum;
import com.horsen.service.base.exception.HseduException;
import com.horsen.service.base.util.ExceptionUtils;
import com.horsen.service.user.controller.BaseController;
import com.horsen.service.user.model.DTO.LoginDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * 管理员 控制器
 *
 * @author Horsen
 */
@Api(tags = "管理员管理")
@ApiSupport(order = 1)
@Slf4j
@RestController
@RequestMapping("/admin/user/admins")
public class AdminController extends BaseController {

    @ApiOperationSupport(order = 1)
    @ApiOperation("获取一个管理员(管理员登录)")
    @PostMapping("/")
    public R login(@RequestBody LoginDTO loginDTO) {
        String token = adminService.login(loginDTO);
        return R.ok("登录成功").setData("token", token);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public R info(@RequestParam String token) {
        try {
            JwtInfo adminInfo = JwtUtils.getAdminByJwtToken(token);
            return R.ok("获得管理员信息成功")
                    .setData("name", adminInfo.getName())
                    .setData("userId", adminInfo.getId())
                    .setData("avatar", adminInfo.getAvatar())
                    .setData("roles", Arrays.asList(adminInfo.getRoles()));
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new HseduException(ResultCodeEnum.FETCH_USER_INFO_ERROR);
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public R logout(@RequestHeader("X-Token") String token) {
        boolean result = JwtUtils.checkJwtToken(token);
        return result ? R.ok("退出登录成功") : R.error("退出登录失败");
    }
}

